//
//  YDStockMarketDetailController.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2018/1/19.
//  Copyright © 2018年 LK-IOS. All rights reserved.
//

#import "YDStockMarketDetailController.h"
#import "YDStockMarketCell.h"
#import "YDStockMarketTableHeaderView.h"
#import "YDStockMarketDetailTopView.h"
#import "YDHomeMarketModel.h"
#import "YDBuyStrategyTitleButton.h"
#import "YDStockMarketPopController.h"
#import "YDStockMarketPopSelectedController.h"
#import "YDBuyStrategyTitleButton.h"
#import "YDStockMarketRiseFallModel.h"
#import "YDVerticalStockBuyController.h"

@interface YDStockMarketDetailController ()<UITableViewDelegate , UITableViewDataSource , UIViewControllerTransitioningDelegate , UIViewControllerAnimatedTransitioning , SYStockMarketPopSelectedControllerDelegate , SYStockMarketTableHeaderViewDelegate>

//tableView
@property (nonatomic , weak) UITableView *tableView;

@property (nonatomic , strong) NSMutableArray *stockModelArray;

@property (nonatomic , weak) UIActivityIndicatorView *activityView;

//大盘数据详情字典
@property (nonatomic , strong) NSMutableDictionary *stockDict;

//行情
@property (nonatomic , weak) YDStockMarketDetailTopView *topView;

@property (nonatomic , weak) YDBuyStrategyTitleButton *button;


//弹出消失
@property (nonatomic , assign) BOOL onAnimate;

//定时器
@property (nonatomic , strong) NSTimer *timer;
//是不是正在刷新
@property (nonatomic , assign) BOOL timerIsRunning;

//定时器
@property (nonatomic , strong) NSTimer *newsTimer;
//是不是正在刷新
@property (nonatomic , assign) BOOL newsTimerIsRunning;

//当前选择加载的股票排行榜类型，
@property (nonatomic , assign) NSInteger risingFallingPricesType;

@end

@implementation YDStockMarketDetailController

-(NSMutableDictionary *)stockDict
{
    if (_stockDict == nil) {
        _stockDict = [NSMutableDictionary dictionary];
    }
    return _stockDict;
}
-(NSMutableArray *)stockModelArray
{
    if (_stockModelArray == nil) {
        _stockModelArray = [NSMutableArray array];
    }
    return _stockModelArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    
    self.risingFallingPricesType = 1;
    
    [self setTitleView];
    [self tableView];
    [self topView];
    [self activityView];
    [self loadMarketDetailData];
    
    [self loadRisingFallingPricesWithTypeIndex:self.risingFallingPricesType];
    //添加通知
    [self addNotification];
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self viewOpenTimer];
    
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self viewStopTimer];
}
-(void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewOpenTimer) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewStopTimer) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewStopTimer) name:UIApplicationWillTerminateNotification object:nil];
}
-(void)dealloc
{
//    DDLog(@"dealloc")
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//定时器
-(void)viewOpenTimer
{
    if (self.timer && self.newsTimer)return;
    if (![NSDate stockTradingTimeJudgment])return;
    DDLog(@"开启定时器")
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timeLoadStockDetailData) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    self.newsTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timeLoadRisingFallingPricesType) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.newsTimer forMode:NSRunLoopCommonModes];
}



-(void)viewStopTimer
{
    if (!self.timer && !self.newsTimer)return;
    DDLog(@"关闭定时器")
    [self.timer invalidate];
    self.timer = nil;
    
    
    [self.newsTimer invalidate];
    self.newsTimer = nil;
    
}

-(void)timeLoadStockDetailData
{
    if (self.timerIsRunning)return;
    self.timerIsRunning = YES;
    NSString *url;
    if (!self.stockCode.length) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"数据加载出错" isExistNav:YES];
        return;
    }else{
        url = [NSString stringWithFormat:@"%@%@",@"/stock/market/" , self.stockCode];
    }
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
        self.timerIsRunning = NO;
        if ([resultDict[@"code"] integerValue] == 200) {
            self.stockDict = [resultDict[@"result"] mutableCopy];
            self.topView.stockDict = [self.stockDict copy];
        }else{
        }
    } failBlock:^(NSError *error) {
        self.timerIsRunning = NO;
    }];
}
-(void)timeLoadRisingFallingPricesType
{
    if (self.newsTimerIsRunning)return;
    self.newsTimerIsRunning = YES;
//    [self.activityView startAnimating];
    NSString *url = [NSString stringWithFormat:@"/stock/%@/ranking?rankType=%@&size=%@" , self.stockCode , [NSNumber numberWithInteger:self.risingFallingPricesType] , [NSNumber numberWithInteger:30]];
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
        self.newsTimerIsRunning = NO;
        DDLog(@"resultDict = %@" , resultDict)
//        [self.activityView stopAnimating];
        if ([resultDict[@"code"] integerValue] == 200) {
            
            NSMutableArray *oldData = [NSMutableArray new];
            oldData = [self.stockModelArray copy];
            
            [self.stockModelArray removeAllObjects];
            
            self.stockModelArray = [YDStockMarketRiseFallModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            
           [self.tableView reloadData];
            
            if (!self.stockModelArray.count || !oldData.count) {
                return ;
            }
            for (int i  = 0; i < self.stockModelArray.count; i++) {
                YDStockMarketRiseFallModel *newModel = [self.stockModelArray objectAtIndex:i];
                YDStockMarketRiseFallModel *oldModel = [oldData objectAtIndex:i];;
                
                
                
                NSInteger newPrice = [[newModel.lastPrice stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
                NSInteger oldPrice = [[oldModel.lastPrice stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
                
                
                
                if (newPrice > oldPrice) {
                    [self startAnimationWithRow:i isUp:YES];
                    continue;
                }else if(newPrice < oldPrice)
                {
                    [self startAnimationWithRow:i isUp:NO];
                    continue;
                }else
                {
                    continue;
                    //价格不变 不做处理
                }
            }
           
            
        }else{
        }
        
    } failBlock:^(NSError *error) {
        DDLog(@"涨跌幅榜单===%@",error);
//        [self.activityView stopAnimating];
        self.newsTimerIsRunning = NO;
    }];
}
//设置导航栏按钮
-(void)setTitleView
{
    YDBuyStrategyTitleButton *button = [YDBuyStrategyTitleButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundColor:[UIColor clearColor]];
    [button setTitle:self.stockName forState:UIControlStateNormal];
    
    [button setImage:[UIImage imageNamed:@"celuexuanze-xia"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"celuexuanze-shang"] forState:UIControlStateSelected];
    
    [button sizeToFit];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    self.navigationItem.titleView = button;
    
}

-(void)buttonClick:(YDBuyStrategyTitleButton *)button
{
    //弹出框的时候，把定时器关闭
    [self viewStopTimer];
    
    button.selected = YES;
    YDStockMarketPopSelectedController *vc = [[YDStockMarketPopSelectedController alloc] init];
    vc.startIndex = self.index;
    vc.modelArray = self.marketModelArray;
    vc.delegate = self;
    vc.transitioningDelegate = self;
    vc.modalPresentationStyle = UIModalPresentationCustom;
    [self.navigationController presentViewController:vc animated:YES completion:nil];
    
    
}

#pragma SYStockMarketPopSelectedControllerDelegate

-(void)dissmissWithoutSelected
{
    //框消失的时候，把定时器打开
    [self viewOpenTimer];
    
    YDBuyStrategyTitleButton *button = (YDBuyStrategyTitleButton *)self.navigationItem.titleView;
    button.selected = NO;
}

-(void)stockMarketPopSelectedController:(YDStockMarketPopSelectedController *)selectedController didSelectedWhichStock:(NSInteger)stockIndex
{
    
    self.risingFallingPricesType = 1;
    
    self.index = stockIndex;
    
    YDHomeMarketModel *model = self.marketModelArray[stockIndex];
    
    //更新当前指数类型
    self.stockCode = model.code;
    self.stockName = model.name;
    
    //按钮
    YDBuyStrategyTitleButton *button = (YDBuyStrategyTitleButton *)self.navigationItem.titleView;
    button.selected = NO;
    [button setTitle:model.name forState:UIControlStateNormal];
    
    //分时数据
    self.topView.stockName = model.name;
    self.topView.stockCode = model.code;
    [self loadMarketDetailData];
    [self loadRisingFallingPricesWithTypeIndex:self.risingFallingPricesType];
    
    //框消失的时候，把定时器打开
    [self viewOpenTimer];
    
}

/**
 tableView
 */
-(UITableView *)tableView
{
    if (_tableView == nil) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, self.view.height - self.tabBarController.tabBar.height - 10) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.backgroundColor = [UIColor colorWithHexString:mainGray];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
    }
    return _tableView;
}

/**
topView
 */
-(YDStockMarketDetailTopView *)topView
{
    if (_topView == nil) {
        CGRect topFrame;
        if (isPhoneX) {
            topFrame = CGRectMake(0, 0, LKScreenW, rateX812(435));
        }else{
            topFrame = CGRectMake(0, 0, LKScreenW, rate750(435));
        }
        YDStockMarketDetailTopView *topView = [YDStockMarketDetailTopView stockMarketDetailTopViewWithFrame:topFrame StockDict:[self.stockDict copy] StockName:self.stockName StockCode:self.stockCode];
        topView.userInteractionEnabled = YES;
        topView.frame = topFrame;
        topView.y = -topView.height;
        self.tableView.tableHeaderView = topView;
        
        _topView = topView;
    }
    return _topView;
}


//加载大盘详情数据
-(void)loadMarketDetailData
{
    NSString *url;
    if (!self.stockCode.length) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"数据加载出错" isExistNav:YES];
        return;
    }else{
        url = [NSString stringWithFormat:@"%@%@",@"/stock/market/" , self.stockCode];
    }
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
        if ([resultDict[@"code"] integerValue] == 200) {
            self.stockDict = [resultDict[@"result"] mutableCopy];
            self.topView.stockDict = [self.stockDict copy];
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"数据加载出错" isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"数据加载出错" isExistNav:YES];
    }];
}





-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.stockModelArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return isPhoneX ? rateX812(40) : rate750(40);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return isPhoneX ? rateX812(50) : rate750(50);
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    YDStockMarketTableHeaderView *header = [YDStockMarketTableHeaderView headerViewWithTableView:tableView];
    header.delegate = self;
    return header;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDStockMarketCell *cell = [YDStockMarketCell cellWithTableView:tableView];
    YDStockMarketRiseFallModel *model = self.stockModelArray[indexPath.row];
    cell.model = model;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDStockMarketRiseFallModel *model = self.stockModelArray[indexPath.row];
    YDVerticalStockBuyController *vc = [[YDVerticalStockBuyController alloc] init];
    vc.isNormal = self.isNormal;
    vc.isActivity = NO;
    vc.isPopToRootC = NO;
    vc.optionStyle = SYVerticalStockButtonOptionViewStyle3;
    vc.stockCode = model.instrumentId;
    vc.stockName = model.name;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

///////******SYStockMarketTableHeaderViewDelegate*******///////
-(void)stockMarketTableHeaderView:(YDStockMarketTableHeaderView *)headerView didClickButton:(YDBuyStrategyTitleButton *)button
{
    //1涨幅榜，2跌幅榜，3价格降序，4，价格升序
    if (button.tag == 202) {
        if (button.selected) {
            self.risingFallingPricesType = 4;
        }else{
            self.risingFallingPricesType = 3;
        }
    }else if (button.tag == 203){
        if (button.selected) {
            self.risingFallingPricesType = 2;
        }else{
            self.risingFallingPricesType = 1;
        }
    }
    [self loadRisingFallingPricesWithTypeIndex:self.risingFallingPricesType];
}


-(void)loadRisingFallingPricesWithTypeIndex:(NSInteger)index
{
    [self.activityView startAnimating];
    NSString *url = [NSString stringWithFormat:@"/stock/%@/ranking?rankType=%@&size=%@" , self.stockCode , [NSNumber numberWithInteger:index] , [NSNumber numberWithInteger:30]];
    //rankType
    //size
    
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
        DDLog(@"resultDict = %@" , resultDict)
        [self.activityView stopAnimating];
        if ([resultDict[@"code"] integerValue] == 200) {
            [self.stockModelArray removeAllObjects];
            
            self.stockModelArray = [YDStockMarketRiseFallModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            
            [self.tableView reloadData];

            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"涨跌榜数据加载出错" isExistNav:YES];
        }
        
    } failBlock:^(NSError *error) {
        [self.activityView stopAnimating];
        DDLog(@"error = %@" , error)
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"涨跌榜数据加载出错" isExistNav:YES];
    }];
}

- (void)startAnimationWithRow:(NSInteger)index isUp:(BOOL)isUp;
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    YDStockMarketCell*cell = (YDStockMarketCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    
    [UIView animateWithDuration:1
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         
                         cell.bgView.backgroundColor = [UIColor colorWithHexString:isUp ? @"#FFE8E5" :@"#E2F6DB"];
                         cell.bgView.alpha = 0.8;
                         
                         
                     } completion:^(BOOL finished) {
                         
                         [UIView animateWithDuration:1 animations:^{
                             cell.bgView.backgroundColor = [UIColor whiteColor];
                             cell.bgView.alpha = 1;
                         }];
                         
                     }];
    
    
}


-(UIActivityIndicatorView *)activityView
{
    if (_activityView == nil) {
        UIActivityIndicatorView *activityView = [UIActivityIndicatorView new];
        [self.view addSubview:activityView];
        activityView.hidesWhenStopped = YES;
        activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        activityView.frame = CGRectMake(0, isPhoneX ? rateX812(500) : rate750(500), rate375(20), rate375(20));
        activityView.centerX = self.view.centerX;
        _activityView = activityView;
    }
    return _activityView;
}



#pragma mark  UIViewControllerTransitioningDelegate , UIViewControllerAnimatedTransitioning
//拿到负责自定义动画的控制器
-(UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source
{
    
    return [[YDStockMarketPopController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
    
}
//谁负责弹出动画
-(id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    self.onAnimate = NO;
    return self;
}
//谁负责消失动画
-(id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    self.onAnimate = YES;
    return self;
}


#pragma mark UIViewControllerAnimatedTransitioning
//返回一个弹出和消失的时间
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext
{
    return 0.5;
}

//实现代理方法.做自定义转场动画
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
    if (self.onAnimate) {//弹出
        [self animateTransitionPresentedController:transitionContext];
    }else{//消失
        [self animateTransitionDismissedController:transitionContext];
    }
    
}

//弹出时调用
-(void)animateTransitionPresentedController:(id <UIViewControllerContextTransitioning>)transitionContext
{
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    [[transitionContext containerView] addSubview:toView];
    
    //    toView.transform = CGAffineTransformMakeScale(0.0, 0.0);
    toView.alpha = 0.0;
    [UIView animateWithDuration:duration animations:^{
        //        toView.transform = CGAffineTransformIdentity;
        toView.alpha = 1.0;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
}
//消失时调用
-(void)animateTransitionDismissedController:(id <UIViewControllerContextTransitioning>)transitionContext
{
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    [UIView animateWithDuration:duration animations:^{
        //        fromView.transform = CGAffineTransformMakeScale(0.00001, 0.00001);
        fromView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
}




@end
